package com.zs4sdk.demo;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.common.library.listener.OnProcessListener;
import com.zs4sdk.Zs4Game;
import com.zs4sdk.common.Extra;
import com.zs4sdk.extra.Zs4GameCode;
import com.zs4sdk.extra.Zs4GameInfo;
import com.zs4sdk.extra.Zs4GameUserInfo;

import java.util.Random;

/**
 * Created by aXiBa on 2017/4/24.
 */
//com.zs4sdk.demo.GameDemoAct
public class GameDemoAct extends Activity implements View.OnClickListener {

    //SDK测试
  //  public static final int APPID = 1000;
   // public static final String APPKEY = "0a305ff02845aacdbf9a8dd75c3b8316";
   public static final int APPID = 8015;

    public static final String APPKEY = "ead4a889f9b84b4fd648cd1ee6b77ef5";

    // 屏幕方向
    public static int APP_SCREEN_ORIENTATION = Zs4Game.SCREEN_ORIENTATION_PORTRAIT;    // 竖屏
//    public static int APP_SCREEN_ORIENTATION = ZayaGame.SCREEN_ORIENTATION_LANDSCAPE;    // 横屏
//    public static int APP_SCREEN_ORIENTATION = ZayaGame.SCREEN_ORIENTATION_SENSOR_LANDSCAPE;    // 横屏(支持翻转)


    TextView text_message;

    Random random = new Random();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Extra.URL.init();
        super.onCreate(savedInstanceState);
        setRequestedOrientation(APP_SCREEN_ORIENTATION);
        setContentView(R.layout.act_game_main);
        initView();

        // TODO 初始化SDK
        initSDK();

        // 设置消息回调
        Zs4Game.getInstance().setMessageCallBack(messageOnProcessListener);
    }

    private void initView() {
        findViewById(R.id.btn_game_login).setOnClickListener(this);
        findViewById(R.id.btn_game_upinfo).setOnClickListener(this);
        findViewById(R.id.btn_game_pay).setOnClickListener(this);
        findViewById(R.id.btn_game_logout).setOnClickListener(this);
        findViewById(R.id.btn_game_exit).setOnClickListener(this);

        text_message = (TextView) findViewById(R.id.text_message);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //登录按钮
            case R.id.btn_game_login:
                if (Zs4Game.getInstance().isLogined()) {
                    Toast.makeText(GameDemoAct.this, "已经登录过了哦~", Toast.LENGTH_LONG).show();
                } else {
                    gotoLogin();
                }
                break;

            //报道角色信息
            case R.id.btn_game_upinfo:
                if (Zs4Game.getInstance().isLogined()) {
                    setExtendData();
                } else {
                    Toast.makeText(GameDemoAct.this, "请先登录", Toast.LENGTH_LONG).show();
                }
                break;

            //支付商品
            case R.id.btn_game_pay:
                if (Zs4Game.getInstance().isLogined()) {
                    pay();
                } else {
                    Toast.makeText(GameDemoAct.this, "请先登录", Toast.LENGTH_LONG).show();
                }
                break;

            //注销操作
            case R.id.btn_game_logout:
                if (Zs4Game.getInstance().isLogined()) {
                    logout();
                } else {
                    Toast.makeText(GameDemoAct.this, "请先登录", Toast.LENGTH_LONG).show();
                }
                break;

            //注销操作
            case R.id.btn_game_exit:
                Zs4Game.getInstance().onExitzs4gameGame(this);
                break;
        }

    }


    /**
     * 初始化SDK
     */
    private void initSDK() {

        // 设置屏幕方向
        Zs4Game.getInstance().setScreenOrientation(APP_SCREEN_ORIENTATION);
        Zs4Game.getInstance().setShowLog(true);

        // app信息
        Zs4GameInfo zs4GameInfo = new Zs4GameInfo(this);

        Zs4Game.getInstance().init(zs4GameInfo, new OnProcessListener() {

            @Override
            public void finishProcess(int code, Bundle bundle) {
                Log.e("code"," finishProcess 11 code is "+code);
                // 初始化完成
                if (Zs4GameCode.INITCOMPLETE == code) {

                    //初始化成功可以调用登录
                    //也可以在用户点击登录的时候再调用登录
                    //但是！！！最好是初始化成功直接调用
                    gotoLogin();
                }
                // 强制版本更新，最好退出游戏
                else if (Zs4GameCode.UPDATEVERSION_FORCE_DOWNING == code) {
                    finish();
                    System.exit(0);
                }
                // 没有sd卡
                else if (Zs4GameCode.UPDATEVERSION_UNMOUNTED_SDCARD == code) {
                    Toast.makeText(GameDemoAct.this, "没有sd卡，请检查！", Toast.LENGTH_LONG).show();
                }
                // 错误: 没有网络或其他错误
                else if (Zs4GameCode.ERROR == code) {
                    Toast.makeText(GameDemoAct.this, bundle.getString(Zs4Game.ERROR_MESSAGE), Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    /**
     * 进行登录（初始化成功或者注销后进行调用）
     */
    private void gotoLogin() {
        Zs4Game.getInstance().login(GameDemoAct.this, new OnProcessListener() {

            @Override
            public void finishProcess(int code, Bundle bundle) {
                Log.e("code","finishProcess success is "+code);
                if (Zs4GameCode.LOGINSUCCESS == code) {
                    setExtendData();
                } else if (Zs4GameCode.ERROR == code) {
                    Toast.makeText(GameDemoAct.this, "登录失败", Toast.LENGTH_LONG).show();
                } else if (Zs4GameCode.BACKTOGAME == code) {

                    Toast.makeText(GameDemoAct.this, "回到游戏", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    /**
     * 登录或者切换账号成功后获取到角色信息需要进行报道，
     * 否则后面无法完成客服以及支付页面的显示以及功能
     */
    private void setExtendData() {


        // 获取并显示用户信息
        Zs4GameUserInfo userInfo = Zs4Game.getInstance().getUserInfo();
        Log.e("info"," userInfo is "+userInfo);

        final String roleName = "我的天"; //角色名
        final String roleId = "sdk_test_role_"+userInfo.getUserId();//角色ID
        final int roleLevel = 1;//角色等级

        final String serId = "sdk_test_ser_001";//角色所在区服ID
        final String serName = "一区—我想放假";//角色所在区服名字

        String info = "\n当前用户ID  :  " + userInfo.getUserId() +
                "\n当前用户名称  :  " + userInfo.getNickName() +
                "\n当前用户token  :  " + userInfo.getUserToken() +
                "\n是否实名认证  :  " + userInfo.isVerify() + "\n" +
                "\n角色ID  :  " + roleId +
                "\n角色名称  :  " + roleName +
                "\n角色等级  :  " + roleLevel + "\n" +
                "\n区服ID  :  " + serId +
                "\n区服名称  :  " + serName;

        if (null != userInfo) {
            text_message.setText("用户信息: " + info);
        }

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("角色信息收集");
        builder.setMessage(info);
        builder.setPositiveButton("必须报道", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Zs4Game.getInstance().setPlayerAndServerInfo(roleId, roleName, roleLevel, serId, serName);
            }
        });
        AlertDialog dialog = builder.create();
        dialog.setCancelable(false);
        dialog.show();
    }

    /**
     * 调用充值接口
     */
    private void pay() {
        final String goodCode = "1178";//商品ID
        final String goodOrderId = "SDK_test_orderId_" + System.currentTimeMillis() / 1000L + "";//订单号(demo使用时间戳做事例，请CP根据自己的需求进行填写)
        final String payExpandData = System.currentTimeMillis() / 1000L + "";//客户端需要传递给服务端的额外参数(demo以时间戳为例，CP可以根据自己需求传值)
        final int randomInt = random.nextInt(3) + 1;//生成随机数表示充值份数

        String info = "商品代码  :  " + goodCode +
                "\nCP订单号  :  " + goodOrderId +
                "\n商品单价  :  " + 6 +
                "元\n购买份数  :  " + randomInt +
                "份\n额外参数  :  " + payExpandData;

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("支付信息");
        builder.setMessage(info);
        builder.setPositiveButton("模拟提交信息进行支付", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                //设置额外参数
                Zs4Game.getInstance().setPayExpandData(payExpandData);
                //调用充值接口
                Zs4Game.getInstance().enterPaymentCenter(
                        GameDemoAct.this,
                        goodCode,//商品ID
                        goodOrderId,//订单号(demo使用时间戳做事例，请CP根据自己的需求进行填写)
                        6,//单价
                        randomInt,//表示充值份数，如果游戏没有同时购买同一个商品多份的请填写默认值 1
                        messageOnProcessListener);

            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }


    /**
     * function: 注销
     *
     * @ author: aXiBa 2013-10-15 下午6:30:09
     */
    private void logout() {

        // sdk账号注销
        Zs4Game.getInstance().logout(GameDemoAct.this, new OnProcessListener() {

            @Override
            public void finishProcess(int code, Bundle bundle) {

                if (Zs4GameCode.LOGOUTSUCCESS == code) {
                    text_message.setText("还没有登录，快快登录吧！");
                    gotoLogin();
                } else if (Zs4GameCode.ERROR == code) {
                    Toast.makeText(GameDemoAct.this, bundle.getString(Zs4Game.ERROR_MESSAGE), Toast.LENGTH_LONG).show();
                } else if (Zs4GameCode.BACKTOGAME == code) {

                    Toast.makeText(GameDemoAct.this, "回到游戏", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    /**
     * 必须
     * 设置全局消息接收处理
     * 用于接收悬浮窗功能操作以及支付等功能的监听
     */
    OnProcessListener messageOnProcessListener = new OnProcessListener() {

        @Override
        public void finishProcess(int code, Bundle bundle) {
            Log.e("code","finishProcess code is  "+code);
            switch (code) {

                case Zs4GameCode.SWITCHACCOUNT:
                    //切换账号
                    setExtendData();
                    break;
                case Zs4GameCode.LOGINSUCCESS:
                    setExtendData();
                    break;
                // 注销
                case Zs4GameCode.LOGOUTSUCCESS:
                    text_message.setText("还没有登录，快快登录吧！");
                    // 重新登录游戏
//                    gotoLogin();

                    break;

                // 支付完成
                case Zs4GameCode.PAYCOMPLETE:

                    int payresult= bundle.getInt(Zs4Game.TPYE);
                    String result= "";
                    if(payresult == Zs4GameCode.PAYTYPE_SECURE){
                        result = "支付成功";
                    }else if(payresult == Zs4GameCode.PAYSECURE_FAIL){
                        result = "支付失败";
                    }else if(payresult == Zs4GameCode.PAYSECURE_CANCEL){
                        result = "支付取消";
                    }

                    String payResult = "支付结果类型:" + result
                            + "  订单号：" + bundle.getString(Zs4Game.KEY_ORDER_CODE);
                    text_message.setText(payResult);
                    Toast.makeText(GameDemoAct.this, "支付类型..:" + bundle.getInt(Zs4Game.TPYE)
                            + "  订单号：" + bundle.getString(Zs4Game.KEY_ORDER_CODE), Toast.LENGTH_SHORT).show();
                    break;
                case Zs4GameCode.BACKTOGAME:
                    Toast.makeText(GameDemoAct.this, "回到游戏", Toast.LENGTH_SHORT).show();
                    break;
                case Zs4GameCode.ERROR:
                    Toast.makeText(GameDemoAct.this, bundle.getString(Zs4Game.ERROR_MESSAGE), Toast.LENGTH_LONG).show();
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    public void onStop() {
        super.onStop();
        //在游戏Activity中的onStop中调用
        Zs4Game.getInstance().onStop(this);
        Log.e("MainAct", "onStop");
    }


    @Override
    public void onResume() {
        //在游戏Activity中的onResume中调用
        Zs4Game.getInstance().onResume(this);
        Log.e("MainAct", "onResume");
        super.onResume();
    }

    @Override
    public void onPause() {
        //在游戏Activity中的onPause中调用
        Zs4Game.getInstance().onPause(this);
        Log.e("MainAct", "onPause");
        super.onPause();
    }

    @Override
    public void onRestart() {
        //在游戏Activity中的onRestart中调用
        Zs4Game.getInstance().onRestart(this);
        Log.e("MainAct", "onRestart");
        super.onRestart();
    }

    @Override
    public void onBackPressed() {
        Zs4Game.getInstance().onBackPressed(this);
        Log.e("MainAct", "onBackPressed");
    }


    @Override
    protected void onStart() {
        Zs4Game.getInstance().onStart(this);
        super.onStart();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        Zs4Game.getInstance().onNewIntent(intent);
        super.onNewIntent(intent);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        Zs4Game.getInstance().onConfigurationChanged(newConfig);
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Zs4Game.getInstance().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 移除监听
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Zs4Game.getInstance().removeMessageCallBack(messageOnProcessListener);
    }
}
